﻿<!DOCTYPE html>
<html>
<head>
    <title>JS Strings Exercise 6</title>
    <link href="styles/js-console.css" rel="stylesheet" />
</head>
<body>
    <h1>Function that extracts the content of a html page given as text.</h1>
    <label for="str-input">String:</label>
    <input type="text" id="str-input" />
    <button onclick="execute()">execute</button>
    <div id="js-console"></div>
    <script src="scripts/js-console.js"></script>
    <script>
        // Get next tag name, start index and end index
        function getNextTag(text, start)
        {
            var openIdx = text.indexOf("<", start);
            var closeIdx = text.indexOf(">", start);
            var name = "";

            if ((openIdx >= 0) && (closeIdx > 0))
            {
                name = text.substring(openIdx, closeIdx + 1);
            }

            return {
                tagName: name,
                tagStartIdx: openIdx,
                tagEndIdx: closeIdx
            }
        }
       
        // Main function
        function removeTags(text)
        {
            var strRes = "";
            var currTag;
            var currStart = 0;
            var currFinish = 0;

            do
            {
                var processText;

                currTag = getNextTag(text, currStart);

                // Get text between to tags
                if (currTag.tagName != "")
                {
                    currFinish = currTag.tagStartIdx;
                }
                else
                {
                    currFinish = text.length;
                }
                processText = text.substring(currStart, currFinish);

                // Add string to final result string
                strRes += processText;

                // Calculate start position for the rest of the text to be processed
                currStart = currTag.tagEndIdx + 1;

                // Repeat until there is more tags to process
            } while (currTag.tagName != "");

            return strRes;
        }

        function execute()
        {
            var inpStr = jsConsole.read("#str-input");

            jsConsole.writeLine(removeTags(inpStr));
        }
    </script>
</body>
</html>
